<template>
  <div :style="{padding:padding}">
    <slot :sliceItem="sliceItem"></slot>
  </div>
</template>

<script>
import {throttle} from "../utils/util"
export default {
    props: {
        // 所有的数据项
        items: {
            required: true,
        },
        // 每个item项的高度
        itemHeight: {
            required: true,
        }
    },
    data() {
        return {
            // 滚动的高度
            scrollTop: 0,
            // 视口的高度
            viewportHeight: 0,
            buffer: 5,
        };
    },
    computed: {
        // 已经滚动过的节点
        over() {
            return Math.max(this.scrollTop / this.itemHeight - this.buffer , 0);
        },
        // 当前滚动 + 视口 将要滚动到的节点
        down() {
            return Math.min(
                (this.scrollTop + this.viewportHeight) / this.itemHeight + this.buffer,
                this.items.length
            )
        },
        sliceItem() {
            return this.items.slice(this.over, this.down);
        },
        padding() {
            return `${this.over * this.itemHeight}px 0 ${(this.items.length - this.down) * this.itemHeight}px 0`;
        }
    },
    created() {
        document.addEventListener("scroll", this.onScroll, {
            passive: true
        })
        this.scrollTop = document.documentElement.scrollTop;
        this.viewportHeight = window.innerHeight;
    },
    destroyed() {
        document.removeEventListener("scroll", this.onScroll);
    },
    methods: {
        onScroll: throttle(function() {
            this.scrollTop = document.documentElement.scrollTop;
            this.viewportHeight = window.innerHeight;
        })
    }
}
</script>

<style>

</style>